package br.com.login;

import br.com.TelaPrincipal.Fr_Principal;
import br.com.controler.OperadorControler;
import br.com.modelo.Operador;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import util.JPAUtil;

/**
 *
 * @author Gilberto
 */
public class Login extends javax.swing.JDialog {

    public Login(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        //atalhso botões
        CancelaAction cancelaAction = new CancelaAction();
        btCancela.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancelaAction");
        btCancela.getActionMap().put("cancelaAction", cancelaAction);

        ConfirmaAction confirmaAction = new ConfirmaAction();
        btConfirma.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "confirmaAction");
        btConfirma.getActionMap().put("confirmaAction", confirmaAction);

        //setando usuario e senha OBS. Apagar guando ir para produção
        textUsuario.setText("Maria");
        TextSenha.setText("123");
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        TextSenha = new javax.swing.JPasswordField();
        btCancela = new javax.swing.JButton();
        btConfirma = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Login de Acesso");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 102, 204)));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Usuário:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));

        textUsuario.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                textUsuarioFocusGained(evt);
            }
        });
        jPanel1.add(textUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 160, -1));

        jLabel2.setText("Senha: ");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 30, 50, -1));
        jPanel1.add(TextSenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 50, 160, -1));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1, 400, 120));

        btCancela.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/botaoCancelar.png"))); // NOI18N
        btCancela.setText("Cancela (ESC)");
        btCancela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelaActionPerformed(evt);
            }
        });
        getContentPane().add(btCancela, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 140, 140, -1));

        btConfirma.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/botaoConfirmar.png"))); // NOI18N
        btConfirma.setText("Confirma (F12)");
        btConfirma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConfirmaActionPerformed(evt);
            }
        });
        getContentPane().add(btConfirma, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 140, 140, -1));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-408)/2, (screenSize.height-205)/2, 408, 205);
    }// </editor-fold>//GEN-END:initComponents

    private void btCancelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelaActionPerformed
        sair();
    }//GEN-LAST:event_btCancelaActionPerformed

    private void textUsuarioFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textUsuarioFocusGained
        JPAUtil.retornarFabrica().createEntityManager();
    }//GEN-LAST:event_textUsuarioFocusGained

    private void btConfirmaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirmaActionPerformed
        validaLogin();
    }//GEN-LAST:event_btConfirmaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Login dialog = new Login(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField TextSenha;
    private javax.swing.JButton btCancela;
    private javax.swing.JButton btConfirma;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textUsuario;
    // End of variables declaration//GEN-END:variables

    private void sair() {
        System.exit(0);
    }

    private void validaLogin() {
        if (textUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Informe o usuário!!", "Mensagem do sistema!!", JOptionPane.WARNING_MESSAGE);
        } else if (TextSenha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Informe sua senha!!", "Mensagem do sistema!!", JOptionPane.WARNING_MESSAGE);
        } else {
            Operador func = OperadorControler.realizaLogin(textUsuario.getText(), TextSenha.getText());
            if (func != null && func.getBloqueado().toString().equalsIgnoreCase("S")) {
                String mensagem = "Usuario sem acesso ao sistema\nEntre em contato com seu superior!!";
                JOptionPane.showMessageDialog(null, mensagem, "Mensagem do sistema!!", JOptionPane.WARNING_MESSAGE);
            } else if (func != null && func.getBloqueado().toString().equalsIgnoreCase("N")) {
                //adiciona na sessao
                dispose();
                new Fr_Principal(func).setVisible(true);
            } else {
                //se nao existir retorna
                String mensagem = "Usuario ou senha invalidos!!";
                JOptionPane.showMessageDialog(null, mensagem, "Mensagem do sistema!!", JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    private class ConfirmaAction extends AbstractAction {

        public ConfirmaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            validaLogin();
        }
    }

    private class CancelaAction extends AbstractAction {

        public CancelaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            sair();
        }
    }
}
